package com.firewolf.sesssion;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 作者：刘兴
 * 时间:18/12/5
 **/
public class RedisSessionDao extends AbstractSessionDAO {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    private final String SHIRO_SESSION_KEY = "shiro_sessionkey";

    @Override
    protected Serializable doCreate(Session session) {
        System.out.println("创建Session");
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session,sessionId);
        redisTemplate.opsForHash().put(SHIRO_SESSION_KEY, sessionId.toString(), session);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        System.out.println("获取Session");
        if(sessionId == null)
            return null;
        Object o = redisTemplate.opsForHash().get(SHIRO_SESSION_KEY, sessionId.toString());
        return o == null ? null : (Session) o ;
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        if (session != null && session.getId() != null)
            redisTemplate.opsForHash().put(SHIRO_SESSION_KEY, session.getId().toString(), session);
    }

    @Override
    public void delete(Session session) {
        if (session != null && session.getId() != null)
            redisTemplate.opsForHash().delete(SHIRO_SESSION_KEY, session.getId().toString());
    }

    @Override
    public Collection<Session> getActiveSessions() {
        List<Session> sessions = new ArrayList<>();
        Set<Object> keys = redisTemplate.opsForHash().keys(SHIRO_SESSION_KEY);
        for (Object o : keys) {
            Object sessionObj = redisTemplate.opsForHash().get(SHIRO_SESSION_KEY, o.toString());
            sessions.add((Session) sessionObj);
        }
        return sessions;
    }
}
